package ljc;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
import com.mchange.v2.c3p0.ComboPooledDataSource;
@WebServlet("/register") // 设置 Servlet 映射路径
public class RegisterServlet extends HttpServlet {
    private DataSource dataSource;

    @Override
    public void init() throws ServletException {
        super.init();
        // 从 Web.xml 配置文件读取数据库连接信息
        String dbUrl = getServletContext().getInitParameter("dbUrl");
        String dbUsername = getServletContext().getInitParameter("dbUsername");
        String dbPassword = getServletContext().getInitParameter("dbPassword");

        // 使用 c3p0 数据库连接池，具体实现可以略作调整
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        try {
            cpds.setDriverClass("com.mysql.cj.jdbc.Driver");
            cpds.setJdbcUrl(dbUrl);
            cpds.setUser(dbUsername);
            cpds.setPassword(dbPassword);

        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        dataSource = cpds;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = dataSource.getConnection();
            String sql = "INSERT INTO user (username, password, email, gender, description) VALUES (?, ?, ?, ?, ?)";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, request.getParameter("username"));
            stmt.setString(2, request.getParameter("password"));
            stmt.setString(3, request.getParameter("email"));
            stmt.setString(4, request.getParameter("gender"));
            stmt.setString(5, request.getParameter("description"));
            stmt.executeUpdate();

            response.sendRedirect(request.getContextPath() + "/success.jsp"); // 注册成功跳转
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/error.jsp"); // 注册失败跳转
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        ((ComboPooledDataSource)dataSource).close(); // 关闭数据库连接池
    }
}
